package com.cas.action;

import com.cas.authentication.CustUsernamePasswordCredential;
import org.apereo.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class CaptchaAction extends AbstractAction {

    private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaAction.class);

    public static final String CAPTCHA_KEY = "captcha_key";

    //验证码异常
    private static final String CUSTOM_CAPTCHA_FAIL_EXCEPTION = "custom.captcha.fail.expection";
    //验证码验证失败
    private static final String CUSTOM_CAPTCHA_FAIL_ERROR = "custom.captcha.fail.error";

    @Override
    protected Event doExecute(RequestContext context) throws Exception {
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getNativeResponse();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();
        HttpSession session = request.getSession();
        String captchaKey = (String) session.getAttribute(CAPTCHA_KEY);
        if(null == captchaKey){
            LOGGER.error("验证码验证异常");
            return this.getError(context,CUSTOM_CAPTCHA_FAIL_EXCEPTION);
        }

        CustUsernamePasswordCredential credential = (CustUsernamePasswordCredential) WebUtils.getCredential(context);
        if(null == credential || (null == credential.getCaptcha() || "".equals(credential.getCaptcha().trim()))){
            LOGGER.error("请输入验证码");
            return this.getError(context,CUSTOM_CAPTCHA_FAIL_ERROR);

        }

        String requestCaptcha = credential.getCaptcha();
        if(!captchaKey.toLowerCase().equals(requestCaptcha.toLowerCase())){
            LOGGER.error("验证码错误");
            return this.getError(context,CUSTOM_CAPTCHA_FAIL_ERROR);
        }

        return super.success();
    }

    /**
     * 跳转到错误页
     * @param requestContext
     * @return
     */
    private Event getError(final RequestContext requestContext,String msg) {
        final MessageContext messageContext = requestContext.getMessageContext();
        messageContext.addMessage(new MessageBuilder().error().code(msg).build());
        return getEventFactorySupport().event(this, msg);
    }

}
